import React from 'react';
import { connect, routerRedux } from 'dva';
import { Layout, Card, Input, Button, Row, Col, message} from 'antd';
import { Form } from '@ant-design/compatible';
import { PlusOutlined } from '@ant-design/icons'
import BaseComponent from 'components/BaseComponent';
import './index.less';
const { Content } = Layout;
import $$ from 'cmn-utils'
import { getCoursewareDetail, addCourseware } from '../../CoursewareManage/service'

const { TextArea } = Input;
const createForm = Form.create;
@connect(({ courseware }) => ({
  ...courseware
}))
class EditCourseware extends BaseComponent {
  constructor (props) {
    super(props)

    this.state = {
      name: '',
      id: null,
      url: '',
      pages: [],
      isshow: this.props.isshow
    }
  }

  componentDidUpdate(prevProps, prevState) {
    if(this.props.isshow !== prevProps.isshow) {
      this.setState({
        isshow: this.props.isshow
      })
    }
  }

  componentWillMount() {
    const id = $$.getStore('id')
    if(id) {
      this.setState({
        id: id
      })
      this.getPages(id)
    } else {
      routerRedux.replace('/')
    }
  }

  getPages = (value) => {
    getCoursewareDetail(value).then(resp => {
      if (resp && resp.data && resp.status) {
        this.setState({
          pages: resp.data.pages,
          name: resp.data.name,
          url: resp.data.url
        })
      } else {
        message.error('获取课件详情失败')
      }
    }).catch(err => {
      console.log('获取课件详情失败:', err)
    })
  }

  handleSubmit = (e) => {
    e.preventDefault()
    this.props.form.validateFields((err, values) => {
      
      if (!err) {
        const coursewareId = this.state.id
        const name = values.name
        const pages = this.state.pages
        const temp = []

        pages.map((item, index) => {
          const t = {}
          index = index + 1
          t.idx = values['idx_' + index]
          t.title = values['title_' + index]
          t.content = values['content_' + index]
          t.coursewareId = coursewareId
          t.creator = 1
          t.updater = 1
          temp.push(t)
        })
        const payload = {
          'id': coursewareId,
          'name': name, 
          'creator': 1,
          'updater': 1,
          'pages': temp}
        addCourseware(payload).then(resp => {
          if (resp && resp.status) {
            message.success('发布成功')
            // window.location.href='/'
            this.setState({
              isshow: true
            })
          } else {
            message.error('发布失败')
          }
        }).catch(err => {
          console.log('发布失败:', err)
        })
      }
    })
  }

  addPage = () => {
    const pages = this.state.pages
    if(pages && pages.length >= 5) {
      message.warn('最多添加五张幻灯片')
      return
    }
    const pageTemp = {
      idx: pages && pages.length > 0 ? parseInt(pages.length) + parseInt(1) : 1,
      title: '',
      content: ''
    }
    pages.push(pageTemp)
    this.setState({
      pages: pages
    })
  }

  delPage = (idx) => {
    const pages = this.state.pages
    if(pages && pages.length <= 1) {
      message.warn('至少保留一张幻灯片')
      return
    }
    pages.forEach((item,index,pages) => {
      if(parseInt(index)+1 === idx){
        pages.splice(index,1)
      }
    })  
    this.setState({
      pages: pages
    })
  }

  download = () => {
    window.location.href=this.state.url
  }
  

  render() {
    const { form } = this.props
    const { pages, name, isshow } = this.state
    const { getFieldDecorator } = form

    const formItemLayout = {
      labelCol: { span: 4 },
      wrapperCol: { span: 18 },
    }

    return(
      <Layout className="full-layout page editcourseware-page">
        <Content>
          <Form
            {...formItemLayout}
            layout={'horizontal'}
            onSubmit={this.handleSubmit}
          >
            <Card>
              <Row>
                <Col span={20}>
                  <Form.Item label={'名称'} >
                    {getFieldDecorator('name', {initialValue: name || ''})(<Input placeholder='课件名称' />) }
                  </Form.Item>
                </Col>
                <Col span={4}>
                  
                </Col>
              </Row>
              
            </Card>
            {
              pages.map((item, idx) => {
                idx = idx+1
                return(
                    <Card key={idx}>
                      <Row>
                        <Col span={20}>
                      <Form.Item 
                        style={{display: 'none'}}
                      >
                        {getFieldDecorator('idx_' + idx, {initialValue: idx || 0})(<Input />) }
                      </Form.Item>
                      <Form.Item label={'幻灯片'+idx+'标题'} 
                        style={{paddingBottom: '20px'}}
                        rules={[
                          {
                            required: true,
                            message: '幻灯片标题必填!',
                          },
                        ]}
                      >
                        {getFieldDecorator('title_' + idx, {initialValue:item.title || ''})(<Input placeholder='标题' />) }
                      </Form.Item>
                      <Form.Item label={'幻灯片'+idx+'内容'}
                        rules={[
                          {
                            required: true,
                            message: '幻灯片内容必填!',
                          },
                        ]}
                      >
                        {getFieldDecorator('content_' + idx, {initialValue:item.content || ''})(<TextArea rows={4} placeholder='内容' />) }
                      </Form.Item>
                      </Col>
                      <Col span={4}>
                        {
                          !isshow ?
                            <Button
                              size="large"
                              type="primary"
                              className="login-form-button"
                              onClick={this.delPage.bind(this, idx)}
                            >
                              删除幻灯片
                            </Button>
                          : null
                        }
                        
                      </Col>
                      </Row>
                    </Card>
                )
              })
            }
            <Card>
              {
                !isshow ?
                  <Button
                    size="large"
                    type="dashed"
                    block 
                    className="login-form-button"
                    onClick={this.addPage}
                    style={{marginBottom: '20px'}}
                    icon={<PlusOutlined/>}
                  >
                    添加幻灯片
                  </Button>
                : null
              }
              
              <Form.Item>
                {
                  !isshow ? 
                  <Button
                    size="large"
                    type="primary"
                    htmlType="submit"
                    className="login-form-button"
                  >
                    发布
                  </Button>
                    : <Button
                    size="large"
                    type="primary"
                    onClick={this.download}
                    className="login-form-button"
                  >
                    下载
                  </Button>
                }
              
              </Form.Item>
            </Card>
          </Form>
        </Content>
      </Layout>
    )
  }
}

export default createForm()(EditCourseware);
